package com.forlove.app.splash;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.widget.ImageView;
import android.widget.Toast;

import com.forlove.app.ForloveConfig;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.PermissionsChecker;
import com.forlove.app.common.utils.StatusBarCompat;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.event.EventEntity;
import com.forlove.app.manager.EventManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.LoadGPSAsync;
import com.forlove.app.manager.async.UpLoadContactsAsync;
import com.forlove.app.qselect.MainActivity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;
import com.forlove.app.qselect.login.entity.GpsEntity;
import com.forlove.app.qselect.login.ui.ChoiceNewAgeActivity;
import com.forlove.app.qselect.login.ui.LimitAreaActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.magicwindow.MLinkAPI;
import cn.magicwindow.MLinkAPIFactory;
import cn.magicwindow.MWConfiguration;
import cn.magicwindow.MagicWindowSDK;
import cn.magicwindow.mlink.MLinkCallback;
import cn.magicwindow.mlink.YYBCallback;

/**
 * 启动页
 */
public class WelcomeActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>> {

    @BindView(R.id.image_view_launch)
    ImageView welcome_button;


    private UpLoadContactsAsync upLoadContactsAsync;
    private LoadGPSAsync loadGPSAsync;
    private MLinkAPI mLinkAPI;

    @Override
    public int getLayoutId() {
        return R.layout.activity_welcome;
    }

    private UpLoadContactsAsync createContacts() {
        if (upLoadContactsAsync == null) {
            upLoadContactsAsync = new UpLoadContactsAsync(this);
        }
        return upLoadContactsAsync;
    }

    private LoadGPSAsync createGPSAsync() {
        if (loadGPSAsync == null) {
            loadGPSAsync = new LoadGPSAsync(this);
        }
        return loadGPSAsync;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);
        register();
    }

    @Override
    public void initView() {
        StatusBarCompat.compat(this);
        //上传通讯录
        if (UserManager.getUserLoginState(this) && PermissionsChecker.getContactsPermission(this)) {
            getSupportLoaderManager().restartLoader(UpLoadContactsAsync.ASYNC_ID, null, this);
        }
        if (UserManager.getUserLoginState(this) && PermissionsChecker.getLocationPermission(this)) {
            initGpsLimit();
        }

        String registerId = JPushInterface.getRegistrationID(this);
        LogUtil.e("yjl", "极光id：" + registerId);
        UserManager.saveJPUSHId(this, registerId);
        mHandler = new Handler(getMainLooper());
        LogUtil.e("---------  Channel  ---------");
        LogUtil.e("    " + SystemUtils.getMetaData(this, "UMENG_CHANNEL"));
        LogUtil.e("---------  -------  ---------");

        initMW();
    }

    private void jumpToMainActivity() {
        if (mHandler == null) {
            mHandler = new Handler(getMainLooper());
        }

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                final String version = SystemUtils.getAppVersionName(WelcomeActivity.this);
                if (!version.equals(UserManager.getOldAppVersion(WelcomeActivity.this))) {
                    intent.setClass(WelcomeActivity.this, GuideActivity.class);
                    //保存当前版本号和重置第一次打开状态
                    UserManager.saveOldAppVersion(WelcomeActivity.this, version);
                    UserManager.saveFirstOpenState(WelcomeActivity.this, false);
                } else {
                    if (UserManager.getUserLoginState(WelcomeActivity.this)) {
                        Bundle bundle = new Bundle();
                        bundle.putInt(MainActivity.Key_Comefrom, MainActivity.COME_FROM_WELCOME);
                        intent.putExtras(bundle);
                        intent.setClass(WelcomeActivity.this, MainActivity.class);
//                        intent.setClass(WelcomeActivity.this, SetUserInfoActivity.class);
//                        intent.setClass(WelcomeActivity.this, AddFriendGuideActivity.class);
                    } else {
//                        intent.setClass(WelcomeActivity.this, ChoiceAgeActivity.class);
                        intent.setClass(WelcomeActivity.this, ChoiceNewAgeActivity.class);
                    }
                }
                startActivity(intent);
                finish();
            }
        }, 2000);
    }

    //初始化磨窗
    public void initMW() {
        MWConfiguration config = new MWConfiguration(this);
        config.setLogEnable(ForloveConfig.IS_DEBUG);//打开魔窗Log信息
        MagicWindowSDK.initSDK(config);
        register();
    }

    private void register() {
        mLinkAPI = MLinkAPIFactory.createAPI(this);
        mLinkAPI.registerDefault(new MLinkCallback() {
            @Override
            public void execute(Map<String, String> paramMap, Uri uri, final Context context) {
//                LogUtil.e("yjl", "registerDefault uri:" + uri);
                final String mobile = paramMap.get("mobile");
                toOtherActivity(mobile);
            }
        });
        //浏览器打开
        mLinkAPI.register("qyq_userinfo", new MLinkCallback() {
            public void execute(Map<String, String> paramMap, Uri uri, final Context context) {
//                LogUtil.e("yjl", "register uri:" + uri);
                //浏览器和应用宝打开会走这里
                final String mobile = paramMap.get("mobile");
                toOtherActivity(mobile);

            }
        });
        if (getIntent().getData() != null) {
            mLinkAPI.router(getIntent().getData());
        } else {
            mLinkAPI.checkYYB(this, new YYBCallback() {
                @Override
                public void onFailed(Context context) {

//                    LogUtil.e("yjl", "onFailed:" + mLinkAPI.getParam("mobile"));
                    //应用宝打开失败
                    jumpToMainActivity();
                }

                @Override
                public void onSuccess() {
                    //应用宝打开成功
//                    LogUtil.e("yjl", "onSuccess mobile:" + mLinkAPI.getParam("mobile"));


                }
            });
        }
    }

    private void toOtherActivity(final String mobile) {
        LogUtil.e("yjl", "toOtherActivity:" + mobile);
        if (StringUtils.isNotEmpty(mobile) && mHandler != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Bundle bundle = new Bundle();
                    bundle.putInt(MainActivity.Key_Comefrom, MainActivity.COME_TO_WEB);
                    bundle.putString("mobile", mobile);
                    if (!UserManager.getUserLoginState(WelcomeActivity.this)) {
                        Intent intent = new Intent(WelcomeActivity.this, ChoiceNewAgeActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        toMainActivity(bundle);
                    }
                }
            }, 2000);

        } else {
            jumpToMainActivity();
        }
    }

    private void initGpsLimit() {
        getSupportLoaderManager().restartLoader(LoadGPSAsync.ASYNC_ID, null, new LoaderManager.LoaderCallbacks<GpsEntity>() {
            @Override
            public Loader<GpsEntity> onCreateLoader(int id, Bundle args) {
                return createGPSAsync();
            }

            @Override
            public void onLoadFinished(Loader<GpsEntity> loader, GpsEntity data) {
            }

            @Override
            public void onLoaderReset(Loader<GpsEntity> loader) {

            }
        });

    }

    @Override
    public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
        return createContacts();
    }

    @Override
    public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {

    }

    @Override
    public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false)
    public void onEventMainThread(EventEntity event) {
        if (event != null && event.eventId == EventManager.EVENT_LIMIT_LOGIN) {
            LogUtil.e("yjl", "event id:" + event.eventId + "   evien name:" + event.eventName);
            if (NetworkUtils.instance(this).isNetworkAvailable()) {
                Intent intent = new Intent(this, LimitAreaActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            } else {
                Toast.makeText(this, "请检查网络！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(UpLoadContactsAsync.ASYNC_ID);
        getSupportLoaderManager().destroyLoader(LoadGPSAsync.ASYNC_ID);
        if (upLoadContactsAsync != null) {
            upLoadContactsAsync.stopLoading();
            upLoadContactsAsync = null;
        }
        if (loadGPSAsync != null) {
            loadGPSAsync.stopLoading();
            loadGPSAsync = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

}
